<?php
/**
 * @title 648. 单词替换 - 哈希
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param String[] $dict
     * @param String $sentence
     * @return String
     */
    function replaceWords($dict, $sentence) {
        /**
         * @since 2020-08-18 哈希字典
         */
        $hashs = [];
        $maxlen = 0;
        foreach ($dict as $word){
            $hashs[$word] = 1;
            $maxlen = max($maxlen, strlen($word));
        }

        /**
         * @since 2020-08-18 分隔单词
         */
        $words = explode(" ", $sentence);
        foreach ($words as $key=>$word){
            /**
             * @since 2020-08-18 最后一位匹配不匹配没区别
             */
            $len = min($maxlen, strlen($word)-1);
            // $len = strlen($word)-1;

            /**
             * @since 2020-08-18 逐位匹配
             */
            $prefix = "";
            for ($i=0; $i<$len; $i++){
                $prefix .= $word[$i];
                if(isset($hashs[$prefix])){
                    $words[$key] = $prefix;
                    break;
                } else {}
            }
        }

        /**
         * @return
         */
        return implode(" ", $words);
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.18_2.php
 */
$datas = [
    [["cat", "bat", "rat"], "the cattle was rattled by the battery",],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->replaceWords($data[0], $data[1]);
    var_dump($result);
    // if(count($result)<=20){
    //     var_dump($result);
    // } else {
    //     var_dump(count($result));
    // }
    echo str_repeat("<br>", 3);
}
$xhprof->end();
